package Servlets;

import java.io.*;

import javax.servlet.http.*;

import HTMLCrators.*;

public abstract class SuperServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		if (request==null){
			System.out.println("Error 2 SuperServlet");//TODO Error 2 SuperServlet
			return;
		}
		String[] fieldThatMustBe=fieldThatMustBe();
		for(int i=0;i<fieldThatMustBe.length;i++){
			if (haveField(request, fieldThatMustBe[i])==false){
				System.out.println("Error 1 SuperServlet");//TODO Error 1 SuperServlet
				return;
			}
		}
		try {
			buildResponse(request,response);
		} catch (IOException e) {
			System.out.println("Error 3 SuperServlet");//TODO Error 3 SuperServlet
		}
	}

	protected boolean haveField(HttpServletRequest request,String field){
		System.out.println(request);//TODO
		System.out.println(field);//TODO
		if (request.getParameter(field)==null){
			return false;
		}
		if (request.getParameter(field).compareTo("") == 0){
			return false;
		}
		return true;
	}
	
	protected abstract void buildResponse(HttpServletRequest request, HttpServletResponse response)  throws IOException;

	protected String[] fieldThatMustBe(){
		return new String[0];
	}

	protected void writeResponse(HttpServletResponse response, HTMLCreator creator) throws IOException{
		
		response.setContentType("text/html; charset=UTF-8");
		
		PrintWriter out = response.getWriter();
//		OutputStream out2=response.getOutputStream();
//		PrintWriter out = new PrintWriter(new OutputStreamWriter(out2, "UTF8") ,true);
		
		System.out.println("SuperServlet:writeResponse encoding="+response.getCharacterEncoding());//TODO

		creator.init();
		while(creator.haveMoreLines()){
			out.println(creator.nextLine());
		}
		creator.finish();
		out.close();
	}

	protected int fieldToInt(HttpServletRequest request,String field,int default1){		
		try {
			return Integer.parseInt(request.getParameter(field));
		} catch (NumberFormatException e) {
			return default1;
		}
	}

	protected int fieldToInt(HttpServletRequest request,String field){		
		return fieldToInt(request,field,0);
	}
}